﻿namespace App.Web
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Microsoft.Practices.Unity;

    public class CustomServiceLocator : IMvcServiceLocator
    {
        IUnityContainer container;

        public CustomServiceLocator(IUnityContainer container)
        {
            this.container = container;
        }

        public IEnumerable<TService> GetAllInstances<TService>()
        {
            return container.ResolveAll<TService>();
        }

        public IEnumerable<object> GetAllInstances(Type serviceType)
        {
            return container.ResolveAll(serviceType);
        }

        public TService GetInstance<TService>()
        {
            return (TService)Resolve(typeof(TService));
        }

        public TService GetInstance<TService>(string key)
        {
            return (TService)Resolve(typeof(TService), key);
        }

        public object GetInstance(Type serviceType)
        {
            return Resolve(serviceType);
        }

        public object GetInstance(Type serviceType, string key)
        {
            return Resolve(serviceType, key);
        }

        public object GetService(Type serviceType)
        {
            return Resolve(serviceType);
        }

        public void Release(object instance)
        {
            container.Teardown(instance);
        }

        private object Resolve(Type serviceType, string key = null)
        {
            try
            {
                return container.Resolve(serviceType, key);
            }
            catch (Exception ex)
            {
                throw new ActivationException(ex.Message, ex);
            }
        }
    }
}
